import React, { FC, useEffect } from 'react';
import useLocalStorage from '@hooks/useLocalStorage';
import useAsyncTask from '@hooks/useAsyncTask';
// import { useFetch } from "../../hooks/useFetch";
function myApiRequest(data: string) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // resolve("⏰" + data);
      const rnd = Math.random() * 10;
      if (rnd <= 5) {
        resolve(`⏰${data}`);
      } else {
        reject(new Error('😭'));
      }
    }, 2000);
  });
}
const Storage: FC = () => {
  const [name, setName] = useLocalStorage<string>('name', '老袁');
  const task = useAsyncTask(async (data: string) => myApiRequest(data));
  // 这里是大忌！
  // Too many re-renders.
  // setName(Math.random().toString());
  // task.run("🏮");
  useEffect(() => {
    console.log(task.status); // 'IDLE' | 'PROCESSING' | 'ERROR' | 'SUCCESS';
  }, [task.status]);
  // const [response, error, isLoading] = useFetch("index.php");
  return (
    <div>
      {/* {isLoading ? "...."}:{error ? xx : response} */}
      <span>{name}</span>
      <h2>{task.status}</h2>
      <button type="button" onClick={() => task.run('🏮')}>测试</button>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
    </div>
  );
};

export default Storage;
